
import {ElMessage} from 'element-plus'
import { hasPerms } from "@/utils/auth";
import {CopyDocument} from '@element-plus/icons-vue'
import {
  customerPending, customerLogs, getSalesList
} from "@/api/crm";
import { type Ref, reactive, ref, onMounted, h, createVNode } from "vue";
import { copyTextToClipboard,getKeyList,cloneDeep, isAllEmpty,storageLocal, deviceDetection } from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";
import {addDrawer, closeAllDrawer} from "@/components/ReDrawer/index";
import { useRoute } from 'vue-router';
import { SuccessFilled, WarningFilled,Notification } from '@element-plus/icons-vue'
import {message} from "@/utils/message";
import customerDetailForm from "@/views/crm/customerDetail.vue";

export function useOrders(tableRef: Ref) {
  const route = useRoute();
  const form = reactive({
    name: "",
    type: "1",
    search_field: "id",
    search:'',
    tab_id:'1',
    sortField:'release_time',
    order:'desc',
    status: null,
    page: 1,
    limit: 15
  });

  const teamList = ref([]);
  const formRef = ref();
  const shopList = ref([]);
  const sta_order_statc = ref([]);
  const selectValue = ref([]);
  const columnsKey = ref('');
  const dataList = ref([]);
  const loading = ref(true);
  const activeStatus = ref(route.query?.order_status||'-1')
  const tabStats = ref({
    tab_1_count: 0,
    tab_2_count: 0,
    tab_3_count: 0
  });
  const selectedNum = ref(0);
  const financial_status_arr = ref([]);
  const salesman_arr = ref([]);
  const shop_group_list_arr = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0, pageSize: 15,pageSizes: [10,20, 40, 60,100,200],
    currentPage: 1, background: true
  });
  const template_url = ref('');
  function onInputChange(row) {
    row.isModified = true; // 手动标记为已修改
  }
  const dataField = ref(['勾选列','展开','客户ID']);
  const db_fields_all = ref(['勾选列','展开','客户ID']);

  // Email	求和项:SA	归属人	组别	电话号码		最后期限		近期情况		最后购买时间		轮询跟进人	轮询情况

  const last_term_arr = [
    {color:'#f38080',value:'还在复购'},{color:'cyan',value:'已完复购意向'},{color:'#49af49',value:'一周'},{color:'#b1b10f',value:'等待物流'}
  ]
  const poll_arr = [
    {color:'#49af49',value:'无回复'},{color:'#b1b10f',value:'已回复（意向）'},{color:'#f38080',value:'已回复（无意向）'},{color:'cyan',value:'已完复购意向'}
    ,{color:'cyan',value:'解决售后中'},{color:'cyan',value:'已转化'}
  ]
  const tags4 = [
    {color:'#49af49',value:'已回复'},{color:'#b1b10f',value:'未回复'}
  ]

  const columns = ref([
    { label: "勾选列", type: "selection", width: 50,disabled:true,fixed:true},
    { label: "客户ID", prop: "id", width: 100, align: "left",disabled:true,fixed:true,sortable: "custom",cellRenderer: ({ row, index }) => (
        <>
          <el-icon onClick={() => addVisitLog(row.id)}><Notification /></el-icon>
          <el-text type="primary" size="small" data-id={row.id} onClick={seeCustomerDetail} style="padding-left:5px;">
            {row.id}
          </el-text>
          {row.isModified==true&&(hasPerms('customer:btn:allo')||hasPerms('customer:btn:genjin'))? (
            <><br/><el-button type="primary" size="small" onClick={() =>onCustomerOrder(row)} style="padding:0 10px;margin-top:-15px;">保存</el-button></>
          ) : (<></>)
          }
        </>
      ),},
    { label: "邮箱", prop: "email",align:'left', width: 200,fixed:true,sortable: "custom",cellRenderer: ({ row, index }) => (
      <>
        <el-icon v-copy:click={row.email}><CopyDocument /></el-icon>
        {row.email?(row.is_verified==1?<el-icon color="green"><SuccessFilled /></el-icon>:<el-icon><WarningFilled /></el-icon>):''}
        {row.email}</>)
    },
    { label: "轮询跟进人", prop: "poll_saleman_id", width: 150,sortable: "custom",cellRenderer: ({ row, index }) => (
        <el-select size="small" allow-create filterable v-model={row.poll_saleman_id}
                   placeholder="轮询跟进人" disabled={!hasPerms('customer:btn:genjin')} onChange={() =>onInputChange(row)}>
          <el-option key="0" label={row.poll_saleman_id?row.poll_saleman_id:'请分配'} value={0} />
          {salesman_arr.value.map(item => {
            return (
              <el-option key={item.id} label={(item?.site_group[0]>0?(item?.sales_group):(item.dept?.name))+'-'+item.username} value={item.id} disabled={item.status!=1}/>
            );
          })}
        </el-select>
      )},
    { label: "初始归属人", prop: "own_saleman", width: 90 ,
      cellRenderer: ({ row, index }) => (<>{row.own_saleman == 0 ? '-' : row.own_saleman}</>)
    },
    { label: "客户类型", prop: "customer_type", width: 100,cellRenderer: ({ row, index }) => (
      <>
        {row.customer_type == 1 ? '独立站客户' : row.customer_type == 2 ? '私域客户' : '未知'}
      </>)
    },
    { label: "初始SA", prop: "init_spent", width: 110,sortable: "custom" },
    { label: "SA", prop: "sa", width: 100},
    { label: "最近下单时间", prop: "order_at",width: 130,sortable: "custom" },
    { label: "最后付款时间", prop: "last_pay_at", width: 130,sortable: "custom" },
    { label: "最后发货时间", prop: "last_express_at", width: 130,sortable: "custom" },
    { label: "释放时间", prop: "release_time", width: 130,sortable: "custom",
      cellRenderer: ({ row, index }) => (<>{row.release_time == 0 ? '-' : (new Date(row.release_time * 1000).toLocaleString('zh-CN'))}</>) },
    { label: "释放备注", prop: "release_remark",showOverflowTooltip:true,width: 200,sortable: "custom" },
    { label: "最后回访时间", prop: "last_visit_time", width: 130,sortable: "custom" ,
      cellRenderer: ({ row, index }) => (<>{row.last_visit_time == 0 ? '-' : row.last_visit_text}</>)
    },

    // { label: "有效归属人", prop: "effective_id", minWidth: 120,
    //   cellRenderer: ({ row, index }) => (<>{row.effective_id > 0 ? '已分配' : '未分配'}</>)
    // },

    // { label: "轮询情况", prop: "poll_remark", minWidth: 120 },
  ]);

  const searchCondList = ref([
    {name:'客户Id',value:'id'},
    {name:'用户姓名',value:'fullname'},
    {name:'电话',value:'contact'},
    {name:'邮箱',value:'email'},
  ]);

  function onCustomerOrder(row){
    delete row.items;
    delete row.logs;
    customerPending(row,"post").then(res=> {
      if(res.code===0){
        row.isModified = false;
        ElMessage({message: `修改成功`,type: "success"})
        onSearch();
      }else{
        message(`失败，原因：${res.message}`, { type: "error"});
      }
    })
  }

  async function onSearch() {
    form.page = pagination.currentPage
    form.limit = pagination.pageSize
    loading.value = true;

    try {
      // 不需要设置额外的查询条件，后端会根据tab_id自动处理
      const response = await customerPending(form);

      // 检查响应数据结构
      if (!response || !response.data) {
        console.error('API响应数据结构异常:', response);
        message('获取数据失败，响应格式异常', { type: "error" });
        loading.value = false;
        return;
      }

      const { data } = response;

      // 检查数据字段是否存在，提供默认值
      dataField.value = data.db_fields || [];
      db_fields_all.value = data.db_fields_all || [];

      dataList.value = data.data || [];
      shopList.value = data.shop_list || [];
      searchCondList.value = data?.search_cond_arr || [];
      financial_status_arr.value = data?.financial_status_arr || [];

      // 设置统计数据
      if (data.tab_stats) {
        tabStats.value = data.tab_stats;
      }
      shop_group_list_arr.value = data?.shop_group_list || [];
      template_url.value = data.template_url || '';

      selectValue.value = data.selectValue || [];
      pagination.total = data.total || 0;
      pagination.pageSize = data.per_page || 15;
      pagination.currentPage = data.current_page || 1;

      setTimeout(() => {
        loading.value = false;
      }, 500);

    } catch (error) {
      console.error('API调用失败:', error);
      message('获取数据失败: ' + error.message, { type: "error" });
      loading.value = false;
    }
  }



  function copy_customer(field){
    const orderlist = dataList.value.filter((item) => item['checked']);
    let textToCopy = '';
    for(let i=0; i<orderlist.length; i++) {
      if(field=='email'){
        textToCopy += orderlist[i]['email'] + '\n';
      }
    }
    copyTextToClipboard(textToCopy.trim());
    ElMessage({
      message: '复制成功',
      type: 'success',
    })
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    form.tab_id = '1';
    onSearch();
  }

  function onSaveCrmBatch(){
    const modifiedList = dataList.value.filter(x=>x.isModified==true);
    const promises = modifiedList.map(row => {
      const rowData = { ...row };
      delete rowData.items;
      delete rowData.logs;
      return customerPending(rowData, "post");
    });

    Promise.allSettled(promises).then(results => {
      let successCount = 0;
      let failCount = 0;

      results.forEach((result, index) => {
        if (result.status === 'fulfilled' && result.value.code === 0) {
          modifiedList[index].isModified = false;
          successCount++;
        } else {
          failCount++;
        }
      });

      if (successCount > 0) {
        ElMessage({message: `批量保存完成：成功${successCount}条，失败${failCount}条`, type: "success"});
        onSearch();
      } else {
        message(`批量保存失败`, { type: "error"});
      }
    });
  }

  function addVisitLog(customerId) {
    // 添加访问日志功能
    console.log('Add visit log for customer:', customerId);
  }

  function seeCustomerDetail(e){
    let customerId = e.target.getAttribute('data-id')
    addDrawer({
      size: '60%',
      title: `客户详情:${customerId}`,
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      hideFooter: true,
      headerStyle:`{ marginBottom: '0px' }`,
      contentRenderer: () =>
        createVNode(customerDetailForm, {
          formInline: customerId
        }),
    });
  }

  const expandedRowKeys = ref([]);
  const expandStatus = ref(false);
  const stateList = ref([]);
  const statistics = ref({});

  function sortChange(column) {
    form.sortField = column.prop;
    form.order = column.order === 'ascending' ? 'asc' : 'desc';
    onSearch();
  }

  function onSelectionCancel() {
    dataList.value.forEach(item => item.checked = false);
    selectedNum.value = 0;
  }

  function export_data() {
    form.export = 1;
    customerPending(form).then(res => {
      form.export = 0;
      if(res.code === 0) {
        ElMessage({message: `导出成功`, type: "success"});
      }
    });
  }

  function openDialog() {
    // 打开对话框功能
  }

  function handleDelete() {
    // 删除功能
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(selection) {
    selectedNum.value = selection.length;
    dataList.value.forEach(item => {
      item.checked = selection.includes(item);
    });
  }

  function setBatchSearch() {
    // 批量搜索功能
  }

  const getSalemanList = async function (page=1,limit=1000) {
    const {data: salesData} = await getSalesList({page,limit});
    salesman_arr.value = salesData.data || [];
    onSearch();
  }

  onMounted(async () => {
    // 处理URL查询参数
    if (route.query && route.query.tab_id) {
      form.tab_id = route.query.tab_id as string;
    }

    getSalemanList();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    salesman_arr,
    searchCondList,
    expandedRowKeys,
    expandStatus,
    stateList,
    statistics,
    shopList,
    template_url,
    tabStats,
    onSearch,
    onSaveCrmBatch,
    copy_customer,
    resetForm,

    export_data,
    sortChange,
    onSelectionCancel,
    openDialog,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    setBatchSearch
  };
}
